#!/usr/bin/python

### CODE BY KYLE CLEMENS ###
### COPYRIGHT KYLE CLEMENS 2011 ###
### DISTRIBUTED UNDER TERMS OF THE GNU GPL V3 ###

### IMPORTS ###

print "EXTREMELY VERBOSE MODE"
print 'Importing system from os as run'
from os import system as run
print 'Success'
print 'Importing path from os'
from os import path
print 'Success'
print 'Importing getcwd from os'
from os import getcwd
print 'Success'
print 'Importing argv from sys'
from sys import argv
print 'Success'
print 'Importing gnu_getopt from getopt'
from getopt import gnu_getopt
print 'Success'

### END IMPORTS ###

### START DEFAULTS ###

print 'Setting cwd to getcwd from import'
cwd   = getcwd()
print 'Setting starting part to 0'
start = 0     ## Starting part for Multi-Part
print 'Setting Multi-Part mode to false'
multi = False ## Boolean - If Multi-Part is enabled
print 'Setting parts to 0'
parts = 0     ## Number of parts for Multi-Part
print 'Setting -P to false'
bar   = False ## Boolean - If a progress bar is wanted instead of text progress
print 'Setting url to ""'
url   = ""    ## URL set for downloading
print 'Setting -c to 0'
cont  = 0     ## What byte to continue from, added to -C in curl
print 'Setting -z to false'
lz    = False ## Boolean - If a leading zero is needed before 1-9
print 'Setting curl command to ""'
comm  = ""    ## Curl command to process
print 'Setting output name to ""'
out   = ""    ## Output name
print 'Setting appendages to ""'
app   = ""    ## Appendages
print 'Setting directory to ""'
direc = ""    ## Directory to download to

print 'Setting version'
ver  = '1.18'                   ## Version
print 'Setting description'
slo  = 'Simple file downloader' ## Slogan/description
print 'Setting author'
auth = 'Kyle Clemens'           ## Author
print 'Setting email'
emai = 'pippin418@gmail.com'    ## Email
#name = argv[0]                 ## Program name

### END DEFAULTS ###

### START FUNCTIONS ###

print 'Defining help function'
def help(): # Display help function
	print 'HELP FUNCTION CALLED'
	print 'Displaying help'
	print "dl v%s" % ver ## Title
	print slo ## Description/slogan
	print
	print "Syntax:" ## Begin syntax explanation
	print "   dl [OPTION]... [URL/FILE]"
	print "   Example: dl 'http://www.example.com/index.html'"
	print "   Or:      dl -m --parts='13' 'http://www.example.com/part.rar'"
	print "   Notice in the above example that there is not part number in the URL. When you enter the URL, do not include the part number"
	print
	print "Options:" ## Options
	print "   -h, --help        Show this help" # Help then quit
	print "   -v, --version     Show the current version installed."
	print "   -m, --multi-part  Tell dl that it will be downloading multiple file parts" # Sets multi to True
	print "   -P, --progress    Show progress bar rather than text" # Sets bar to True
	print "   -c, --continue=   Tell dl at what byte to begin downloading (default is 0)" # Sets cont to given value
	print "   -o, --output=     Tell dl what filename to output, if none given it will output to the filename in the URL" # Sets output
	print "   -d, --directory=  Tell dl what directory to download to, default is directory dl was called from" # Sets direc
	print
	print "Multi-Part Options:"
	print "   Note that -o, --output= cannot be specified in Multi-Part download"
	print "   -p, --parts=        Set number of parts" # Sets parts to given value
	print "   -z, --leading-zero  Tell dl that a leading zero is necessary before a single-digit part number" # Sets lz to True
	print "   -s, --starting-part Set the starting part number, defaults to 1"
	print "   -P, --progress      Show progress bar rather than text" # Sets bar to True
	print "   -a, --appendages    Sets appendages. See the manpage for further explanation."	
	print "   -d, --directory=  Tell dl what directory to download to, default is directory dl was called from" # Sets direc
	print
	print "See `man dl` for more information."
	print
	print 'Quitting'
	quit()

print 'Defining insert function'
def ins(com, command):
	print 'Splitting command variable'
	command = command.split(" ")
	print 'Inserting command into command variable'
	command.insert(1, com)
	print 'Joining command variable'
	command = ' '.join(command)
	print 'Returning command variable'
	return command

### END FUNCTIONS ###

### START OPTIONS/PARAMETERS ###

print 'Setting parameters to all arguments'
cmdline_params = argv[1:]
print 'Trying to receive'
try:
	opts, args = gnu_getopt(cmdline_params, 'hp:mzc:Ps:o:a:vd:', ['help', 'parts=', 'multi-part', 'leading-zero', 'continue=', 'progress', 'starting-part=', 'output=', 'appendages=', 'version', 'directory='])
except:
	print 'Receiving failed'
	print "Unknown option, now quitting."
	print 'Quitting'
	quit()
print 'Receiving success'
for option, parameter in opts:
	if option in ('-h', '--help'): # This should be pretty straightforward...
		print '-h or --help was found'
		print 'Using help() function'
		help()
	if option in ('-m', '--multi-part'):
		print '-m or --multi-part was found'
		print 'Setting multi to True'
		multi = True
	if option in ('-p', '--parts'):
		print '-p or --parts was found'
		print 'Setting parts to parameter'
		parts = int(parameter)
	if option in ('-z', '--leading-zero'):
		print '-z or --leading-zero was found'
		print 'Setting leading zero to true'
		lz = True
	if option in ('-c', '--continue'):
		print '-c or --continue was found'
		print 'Setting continue to parameter'
		cont = int(parameter)
	if option in ('-P', '--progress'):
		print '-P or --progress was found'
		print 'Setting -P to true'
		bar = True
	if option in ('-s', '--starting-part'):
		print '-s or --starting-part was found'
		print 'Setting start to parameter-1'
		start = int(parameter)-1
	if option in ('-o', '--output'):
		print '-o or --output was found'
		print 'Setting out to parameter'
		out = parameter
	if option in ('-a', '--appendages'):
		print '-a or --appendages was found'
		print 'Setting appendages to parameter'
		app = parameter
	if option in ('-v', '--version'):
		print '-v or --version was found'
		print 'Printing out version, author and email'
		print "dl v"+ver
		print "Made by:"
		print auth + " <" + emai + ">\n"
		print 'Quitting'
		quit()
	if option in ('-d', '--directory'):
		print '-d or --directory was found'
		print "Setting directory to parameter" 
		direc = parameter
		if not path.exists(direc):
			print "Checking if path exists"
			print "Directory '%s' is not existent. Now quitting." % direc
			print "Oops, it does. Quitting."
			quit()

print "Checking for URL"
if len(args) == 1:
	print "Found. Setting url value"
	url = args[0]
else:
	print "Either not found or too many"
	print "Use -h for help."
	quit()

### END OPTIONS/PARAMETERS ###

### START MULTI-PART DOWNLOADER ###

print 'Checking for Multi-Part mode'
if multi:

	## start extension ##
	print "Setting extension"
	print 'Splitting url'
	ext  = url.split('/') # Split url by /
	print 'Finding end of url and setting it'
	ext  = ext[len(ext)-1] # Set ext to the filename
	print "Making backup variable"
	extc = ext # For checking purposes
	print 'Split name again'
	ext  = ext.split('.') # Split ext by . (extension separator)
	print 'Attempting to find extension'
	ext  = '.'+ext[len(ext)-1] # Set ext to the extension
	print 'Added period to extension'
	if extc == ext[1:]: # If there is no extension
		print 'No extension, not set'
		print 'Set to ""'
		ext = "" # Don't set one
	else:
		print "Extension set"
		pass #Otherwise, nevermind
	## end extension ##
	
	while start < parts:
		print "Adding one to starting part"
		start = start + 1 # Add 1 to the part so it will eventually stop
		print 'Checking for leading zero'
		if lz > 0: # If leading zero is set (i.e. above 0)
			print "Leading-zero is ON"
			print 'Checking for single digit'
			if start < 10: # Is it single digit?
				print "Single digit detected, adding 0"
				start = "0" + str(start) # Add 0 to single-digit
		print 'Checking for extension'
		if url.endswith(ext): # Does the URL have the extension?
			print "Detecting and replacing extension"
			url = url.replace(ext, "") # Remove it if it does
		else: # Otherwise
			#print "Something happened. Make an issue at dlv1 on Google Code with the error code 125.\nDebug:\nURL:%s\nEXT:%s" % (url, ext) # Something went wrong
			#quit() # ABORT! IT'S A TRAP!
			print "Already removed extension"
			pass # It's already been removed
		print 'Checking for appendages'
		if url.endswith(app): # If URL ends with appendages
			print "Detecting and removing appendages"
			url = url.replace(app, "") # Remove appendages
		pass
		print "Composing final url"
		fin = url + str(start) + app + ext ## Final url = Base url + current part number + appendages + extension
		print 'Split output to final url'
		out = fin.split("/") # Sets the output to URL
		print 'Output name set'
		out = out[len(out)-1] # Sets output to complete file name
		print 'Checking for directory'
		if direc == "": # If no output directory is set
			print "No directory set, setting to CWD"
			direc = cwd # Set it to directory dl was called from
			if not direc.endswith('/'):
				direc = direc + '/'
			else:
				pass
		print 'Setting curl command'
		comm = "curl -o '%s/%s' '%s'" % (direc, out, fin) # Sets curl command
		print 'Checking for -P'
		if bar: # If bar = True
			print '-P enabled, adding `-#` to curl command'
			comm = ins("-#", comm) # Add -#
		print 'Checking for existent path'
		if path.exists(direc + out):
			print "WARNING: Path exists"
			print 'Asking for input'
			exists = raw_input("File '%s' already exists. Overwrite? [Y/N] " % out)
			if exists in ("y", 'Y'):
				print "Detected `y` or `Y` in input"
				print "Overwriting file '%s'." % out
			else:
				print "Detected negative response in input"
				print "File '%s' not being overwritten." % out
				print "Quitting"
				quit()
		print "Now running curl command"
		run(comm) # Download with curl, run curl command
		print "Resetting part number to integer"
		start = int(start) # Return part to integer so we can continue
	print "All parts received"
	quit() # Quit when you have all parts
print 'Not using Multi-Part mode'
### END MULTI-PART DOWNLOADER ###

### START DOWNLOADER ###
print 'Must be using single part downloader'
print 'Checking for output value'
if out == "": # If no output value was set
	print "No output specified, setting one"
	out = url.split("/") # Split the URL
	print "URL split"
	out = out[len(out)-1] # Find file name and set it to output value
	print "Found URL file name, setting"
print 'Checking for directory'
if direc == "": # If no output directory is set
	print "No directory set, setting to CWD"
	direc = cwd # Set it to directory dl was called from
	if not direc.endswith('/'):
		direc = direc + '/'
	else:
		pass
print "Setting curl command"
comm = "curl -o '%s/%s' '%s'" % (direc, out, url) # Set curl command
print 'Checking for -P'
if bar: # If -P is set
	print "-P is set, adding `-#` to curl command"
	comm = ins("-#", comm) # Add -#
print 'Checking for continue value'
if cont: # If cont value was set
	print "-c was set, now adding `-C %s` to curl command" % cont
	comm = ins("-C %s" % cont, comm)
print 'Checking for existent path'
if path.exists(direc + out):
	print "WARNING: Path exists"
	print "Displaying input dialog"
	exists = raw_input("File '%s' already exists. Overwrite? [Y/N] " % out)
	if exists in ("y", 'Y'):
		print "Detected `y` or `Y` in input"
		print "Overwriting file '%s'." % out
	else:
		print "Detected negative response in input"
		print "File '%s' not being overwritten." % out
		print 'Quitting'
		quit()
print "Running curl command"		
run(comm) # Run curl command

### END DOWNLOADER ###
print "Quit"
quit() # Trailing quit() for safe keeping